/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package pl.tom.social.fetcher.agent.behaviour;

import jade.core.behaviours.CyclicBehaviour;
import jade.lang.acl.ACLMessage;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import pl.tom.social.common.jade.ACLMessageUtils;
import pl.tom.social.common.types.ConversationIDType;
import pl.tom.social.fetcher.jade.LocalJade;

/**
 *
 * @author Tom
 */
public class AdminBehaviour extends CyclicBehaviour {

	private static final Logger logger = Logger.getLogger(AdminBehaviour.class);

	@Override
	public void action() {
		ACLMessage msg = myAgent.blockingReceive();
		if (msg != null) {
			String url = msg.getContent();
			String cId = msg.getConversationId();
			if (cId != null && cId.length() > 0) {
				try {
					ConversationIDType type = ConversationIDType.valueOf(cId);
					switch (type) {
						case AddNewNode:
						case UpdateNode:
							ACLMessage reply = msg.createReply();
							if (LocalJade.getInstance().addFetchNodeAgent(url)) {
								reply.setPerformative(ACLMessage.ACCEPT_PROPOSAL);
							} else {
								reply.setPerformative(ACLMessage.REJECT_PROPOSAL);
							}
							myAgent.send(reply);
							break;
						case CancelNewNode:
							LocalJade.getInstance().cancelFetchNodeAgent(url);
							break;
					}
				} catch (Exception ex) {
					logger.log(Level.ERROR, ex);
				}
			} else {
				logger.log(Level.WARN, "Unknown message\n" + ACLMessageUtils.toString(msg));
			}
		}
	}
}
